package com.ebrg.secure9.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.bouncycastle.util.encoders.Base64;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Contacts;
import android.provider.Contacts.Intents;
import android.text.InputType;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Config;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebrg.secure9.Account;
import com.ebrg.secure9.FontSizes;
import com.ebrg.secure9.Secure9;
import com.ebrg.secure9.Preferences;
import com.ebrg.secure9.activity.setup.EncryptionNewKey;
import com.ebrg.secure9.controller.MessagingController;
import com.ebrg.secure9.controller.MessagingListener;
import com.ebrg.secure9.mail.Address;
import com.ebrg.secure9.mail.Flag;
import com.ebrg.secure9.mail.Message;
import com.ebrg.secure9.mail.MessagingException;
import com.ebrg.secure9.mail.Multipart;
import com.ebrg.secure9.mail.Part;
import com.ebrg.secure9.mail.Message.RecipientType;

import com.ebrg.secure9.mail.internet.MimeUtility;
import com.ebrg.secure9.mail.security.DiffieHellman;
import com.ebrg.secure9.mail.security.Encryptor;
import com.ebrg.secure9.mail.security.Hash;
import com.ebrg.secure9.mail.security.Keys;
import com.ebrg.secure9.mail.store.LocalStore.LocalAttachmentBodyPart;
import com.ebrg.secure9.mail.store.LocalStore.LocalMessage;
import com.ebrg.secure9.mail.store.LocalStore.LocalTextBody;
import com.ebrg.secure9.provider.AttachmentProvider;
import com.ebrg.secure9.R;


@SuppressWarnings("deprecation")
public class MessageView extends K9Activity implements OnClickListener
{
	private static final String EXTRA_MESSAGE_REFERENCE = "com.ebrg.secure9.MessageView_messageReference";
	private static final String EXTRA_MESSAGE_REFERENCES = "com.ebrg.secure9.MessageView_messageReferences";
	private static final String EXTRA_NEXT = "com.ebrg.secure9.MessageView_next";

	private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;

	//Secure9
	private boolean subjectIsEncrypted;
	private static String sender;
	private EditText input;
	private boolean pinMatch;
	private boolean aes256 = false;
	private boolean noCipherText;




	private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
	private TextView mFromView;
	private TextView mDateView;
	private TextView mTimeView;
	private TextView mToView;
	private TextView mCcView;
	private TextView mSubjectView;
	public View chip;
	private CheckBox mFlagged;
	private int defaultSubjectColor;
	private WebView mMessageContentView;
	private LinearLayout mAttachments;
	private LinearLayout mCcContainerView;
	private TextView mAdditionalHeadersView;
	private View mAttachmentIcon;
	private View mDownloadingIcon;
	private View mShowPicturesSection;
	View next;
	View next_scrolling;
	View previous;
	View previous_scrolling;

	private Account mAccount;
	private MessageReference mMessageReference;
	private ArrayList<MessageReference> mMessageReferences;

	private Message mMessage;

	private static final int PREVIOUS = 1;
	private static final int NEXT = 2;

	private int mLastDirection = PREVIOUS;


	private MessageReference mNextMessage = null;
	private MessageReference mPreviousMessage = null;


	private Menu optionsMenu = null;

	private Listener mListener = new Listener();
	private MessageViewHandler mHandler = new MessageViewHandler();

	private FontSizes mFontSizes = Secure9.getFontSizes();

	/**
	 * Pair class is only available since API Level 5, so we need
	 * this helper class unfortunately
	 */
	private class HeaderEntry
	{
		public String label;
		public String value;

		public HeaderEntry(String label, String value)
		{
			this.label = label;
			this.value = value;
		}
	}


	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		boolean ret = false;

		if (KeyEvent.ACTION_DOWN == event.getAction())
		{
			ret = onKeyDown(event.getKeyCode(), event);
		}
		if (ret == false)
		{
			ret = super.dispatchKeyEvent(event);
		}
		return ret;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		switch (keyCode)
		{
		case KeyEvent.KEYCODE_DEL:
		{
			onDelete();
			return true;
		}
		case KeyEvent.KEYCODE_D:
		{
			onDelete();
			return true;
		}
		case KeyEvent.KEYCODE_F:
		{
			onForward();
			return true;
		}
		case KeyEvent.KEYCODE_A:
		{
			onReplyAll();
			return true;
		}
		case KeyEvent.KEYCODE_R:
		{
			onReply();
			return true;
		}
		case KeyEvent.KEYCODE_G:
		{
			onFlag();
			return true;
		}

		case KeyEvent.KEYCODE_M:
		{
			onMove();
			return true;
		}
		case KeyEvent.KEYCODE_Y:
		{
			onCopy();
			return true;
		}
		case KeyEvent.KEYCODE_J:
		case KeyEvent.KEYCODE_P:
		{
			onPrevious(Secure9.isAnimations());
			return true;
		}
		case KeyEvent.KEYCODE_N:
		case KeyEvent.KEYCODE_K:
		{
			onNext(Secure9.isAnimations());
			return true;
		}
		case KeyEvent.KEYCODE_Z:
		{
			if (event.isShiftPressed())
			{
				mHandler.post(new Runnable()
				{
					public void run()
					{
						mMessageContentView.zoomIn();
					}
				});
			}
			else
			{
				mHandler.post(new Runnable()
				{
					public void run()
					{
						mMessageContentView.zoomOut();
					}
				});
			}
			return true;
		}
		case KeyEvent.KEYCODE_H:
		{
			Toast toast = Toast.makeText(this, R.string.message_help_key, Toast.LENGTH_LONG);
			toast.show();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

	class MessageViewHandler extends Handler
	{
		public void progress(final boolean progress)
		{

			runOnUiThread(new Runnable()
			{
				public void run()
				{
					setProgressBarIndeterminateVisibility(progress);

				}
			});
		}

		public void addAttachment(final View attachmentView)
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					mAttachments.addView(attachmentView);
					mAttachments.setVisibility(View.VISIBLE);

				}
			});
		}

		public void setAttachmentsEnabled(final boolean enabled)
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					for (int i = 0, count = mAttachments.getChildCount(); i < count; i++)
					{
						Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag();
						attachment.viewButton.setEnabled(enabled);
						attachment.downloadButton.setEnabled(enabled);
					}

				}
			});
		}

		public void setHeaders(
				final   String subject,
				final   String from,
				final   String date,
				final   String time,
				final   String to,
				final   String cc,
				final   int accountColor,
				final   boolean unread,
				final   boolean hasAttachments,
				final   boolean isDownloading,
				final   boolean flagged,
				final   boolean answered)
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					setTitle(subject);
					if (subject == null || subject.equals(""))
					{
						mSubjectView.setText(getText(R.string.general_no_subject));
					}
					else
					{
						mSubjectView.setText(subject);
					}
					mFromView.setText(from);
					if (date != null)
					{
						mDateView.setText(date);
						mDateView.setVisibility(View.VISIBLE);
					}
					else
					{
						mDateView.setVisibility(View.GONE);
					}
					mTimeView.setText(time);
					mToView.setText(to);

					mCcContainerView.setVisibility((cc != null && cc.length() > 0)? View.VISIBLE : View.GONE);

					mCcView.setText(cc);
					mAttachmentIcon.setVisibility(hasAttachments ? View.VISIBLE : View.GONE);
					mDownloadingIcon.setVisibility(isDownloading ? View.VISIBLE : View.GONE);
					if (flagged)
					{
						mFlagged.setChecked(true);
					}
					else
					{
						mFlagged.setChecked(false);
					}
					mSubjectView.setTextColor(0xff000000 | defaultSubjectColor);

					chip.setBackgroundColor(accountColor);
					chip.getBackground().setAlpha(unread ? 255 : 127);

					if (answered)
					{
						Drawable answeredIcon = getResources().getDrawable(
								R.drawable.ic_mms_answered_small);
						mSubjectView.setCompoundDrawablesWithIntrinsicBounds(
								answeredIcon, // left
								null, // top
								null, // right
								null); // bottom
					}
					else
					{
						mSubjectView.setCompoundDrawablesWithIntrinsicBounds(
								null, // left
								null, // top
								null, // right
								null); // bottom
					}


				}
			});
		}

		public void networkError()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					Toast.makeText(MessageView.this,
							R.string.status_network_error, Toast.LENGTH_LONG).show();

				}
			});
		}

		public void invalidIdError()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					Toast.makeText(MessageView.this,
							R.string.status_invalid_id_error, Toast.LENGTH_LONG).show();

				}
			});
		}

		public void attachmentSaved(final String filename)
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					Toast.makeText(MessageView.this, String.format(
							getString(R.string.message_view_status_attachment_saved), filename),
							Toast.LENGTH_LONG).show();


				}
			});
		}

		public void attachmentNotSaved()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{

					Toast.makeText(MessageView.this,
							getString(R.string.message_view_status_attachment_not_saved),
							Toast.LENGTH_LONG).show();

				}
			});
		}

		public void fetchingAttachment()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					Toast.makeText(MessageView.this,
							getString(R.string.message_view_fetching_attachment_toast),
							Toast.LENGTH_SHORT).show();
				}
			});
		}

		public void showShowPictures(final boolean show)
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					mShowPicturesSection.setVisibility(show ? View.VISIBLE : View.GONE);
				}
			});

		}

		/**
		 * Clear the text field for the additional headers display if they are
		 * not shown, to save UI resources.
		 */
		public void hideAdditionalHeaders()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					mAdditionalHeadersView.setVisibility(View.GONE);
					mAdditionalHeadersView.setText("");
					mTopView.scrollTo(0, 0);
				}
			});
		}

		/**
		 * Set up and then show the additional headers view. Called by
		 * {@link #onShowAdditionalHeaders()} and
		 * {@link #setHeaders(Account, String, String, Message)}
		 * (when switching between messages).
		 */
		public void showAdditionalHeaders()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					Integer messageToShow = null;
					try
					{
						// Retrieve additional headers
						boolean allHeadersDownloaded = mMessage.isSet(Flag.X_GOT_ALL_HEADERS);
						List<HeaderEntry> additionalHeaders = getAdditionalHeaders(mMessage);

						if (!additionalHeaders.isEmpty())
						{
							// Show the additional headers that we have got.
							setupAdditionalHeadersView(additionalHeaders);
							mAdditionalHeadersView.setVisibility(View.VISIBLE);
						}

						if (!allHeadersDownloaded)
						{
							/*
							 * Tell the user about the "save all headers" setting
							 *
							 * NOTE: This is only a temporary solution... in fact,
							 * the system should download headers on-demand when they
							 * have not been saved in their entirety initially.
							 */
							messageToShow = R.string.message_additional_headers_not_downloaded;
						}
						else if (additionalHeaders.isEmpty())
						{
							// All headers have been downloaded, but there are no additional headers.
							messageToShow = R.string.message_no_additional_headers_available;
						}
					}
					catch (MessagingException e)
					{
						messageToShow = R.string.message_additional_headers_retrieval_failed;
					}

					// Show a message to the user, if any
					if (messageToShow != null)
					{
						Toast toast = Toast.makeText(MessageView.this, messageToShow, Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
						toast.show();
					}
				}
			});
		}

		/**
		 * Set up the additional headers text view with the supplied header data.
		 *
		 * @param additionalHeaders
		 *          List of header entries. Each entry consists of a header
		 *          name and a header value. Header names may appear multiple
		 *          times.
		 *
		 * This method is always called from within the UI thread by
		 * {@link #showAdditionalHeaders()}.
		 */
		private void setupAdditionalHeadersView(final List<HeaderEntry> additionalHeaders)
		{
			SpannableStringBuilder sb = new SpannableStringBuilder();
			boolean first = true;
			for (HeaderEntry additionalHeader : additionalHeaders)
			{
				if (!first)
				{
					sb.append("\n");
				}
				else
				{
					first = false;
				}

				StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
				SpannableString label = new SpannableString(additionalHeader.label + ": ");
				label.setSpan(boldSpan, 0, label.length(), 0);

				sb.append(label);
				sb.append(additionalHeader.value.replaceAll("\\r\\n", ""));
			}

			mAdditionalHeadersView.setText(sb);
		}
	}

	class Attachment
	{
		public String name;
		public String contentType;
		public long size;
		public LocalAttachmentBodyPart part;
		public Button viewButton;
		public Button downloadButton;
		public ImageView iconView;
	}

	public static void actionView(Context context, MessageReference messRef, List<MessageReference> messReferences)
	{
		actionView(context, messRef, messReferences, null);
	}

	public static void actionView(Context context, MessageReference messRef, List<MessageReference> messReferences, Bundle extras)
	{
		Intent i = new Intent(context, MessageView.class);
		i.putExtra(EXTRA_MESSAGE_REFERENCE, messRef);
		i.putExtra(EXTRA_MESSAGE_REFERENCES, (Serializable)messReferences);
		if (extras != null)
		{
			i.putExtras(extras);
		}
		context.startActivity(i);
	}

	@Override
	public void onCreate(Bundle icicle)
	{
		super.onCreate(icicle, false);


		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.message_view);


		mFromView = (TextView)findViewById(R.id.from);
		mToView = (TextView)findViewById(R.id.to);
		mCcView = (TextView)findViewById(R.id.cc);
		mCcContainerView = (LinearLayout)findViewById(R.id.cc_container);
		mSubjectView = (TextView)findViewById(R.id.subject);

		defaultSubjectColor = mSubjectView.getCurrentTextColor();

		mAdditionalHeadersView = (TextView)findViewById(R.id.additional_headers_view);

		chip = findViewById(R.id.chip);

		mDateView = (TextView)findViewById(R.id.date);
		mTimeView = (TextView)findViewById(R.id.time);
		mTopView = (ScrollView)findViewById(R.id.top_view);
		mMessageContentView = (WebView)findViewById(R.id.message_content);


		mAttachments = (LinearLayout)findViewById(R.id.attachments);
		mAttachmentIcon = findViewById(R.id.attachment);
		mDownloadingIcon = findViewById(R.id.downloading);
		mShowPicturesSection = findViewById(R.id.show_pictures_section);


		mFlagged = (CheckBox)findViewById(R.id.flagged);
		mFlagged.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				onFlag();
			}
		});

		mMessageContentView.setVerticalScrollBarEnabled(true);
		mMessageContentView.setVerticalScrollbarOverlay(true);
		mMessageContentView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

		final WebSettings webSettings = mMessageContentView.getSettings();

		webSettings.setSupportZoom(true);
		webSettings.setLoadsImagesAutomatically(true);
		//webSettings.setBuiltInZoomControls(true);
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

		webSettings.setTextSize(mFontSizes.getMessageViewContent());

		mFromView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewSender());
		mToView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewTo());
		((TextView)findViewById(R.id.to_label)).setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewTo());
		mCcView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewCC());
		((TextView)findViewById(R.id.cc_label)).setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewCC());
		mSubjectView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewSubject());
		mTimeView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewTime());
		mDateView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewDate());
		mAdditionalHeadersView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getMessageViewAdditionalHeaders());
		mAdditionalHeadersView.setVisibility(View.GONE);
		mAttachments.setVisibility(View.GONE);
		mAttachmentIcon.setVisibility(View.GONE);

		setOnClickListener(R.id.from);
		setOnClickListener(R.id.reply);
		setOnClickListener(R.id.reply_all);
		setOnClickListener(R.id.delete);
		setOnClickListener(R.id.forward);
		setOnClickListener(R.id.next);
		setOnClickListener(R.id.previous);

		// To show full header
		setOnClickListener(R.id.header_container);

		setOnClickListener(R.id.reply_scrolling);
		//       setOnClickListener(R.id.reply_all_scrolling);
		setOnClickListener(R.id.delete_scrolling);
		setOnClickListener(R.id.forward_scrolling);
		setOnClickListener(R.id.next_scrolling);
		setOnClickListener(R.id.previous_scrolling);

		setOnClickListener(R.id.show_pictures);


		setTitle("");

		Intent intent = getIntent();
		Uri uri = intent.getData();

		if (icicle!=null)
		{
			mMessageReference = (MessageReference)icicle.getSerializable(EXTRA_MESSAGE_REFERENCE);
			mMessageReferences = (ArrayList<MessageReference>)icicle.getSerializable(EXTRA_MESSAGE_REFERENCES);
		}
		else
		{
			if (uri==null)
			{
				mMessageReference = (MessageReference)intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE);
				mMessageReferences = (ArrayList<MessageReference>)intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCES);
			}
			else
			{
				List<String> segmentList = uri.getPathSegments();
				if (segmentList.size()==3)
				{
					String accountId = segmentList.get(0);
					Account[] accounts = Preferences.getPreferences(this).getAccounts();
					boolean found = false;
					for (Account account : accounts)
					{
						if (String.valueOf(account.getAccountNumber()).equals(accountId))
						{
							mAccount = account;
							found = true;
							break;
						}
					}
					if (!found)
					{
						//TODO: Use resource to externalize message
						Toast.makeText(this, "Invalid account id: " + accountId, Toast.LENGTH_LONG).show();
						return;
					}

					mMessageReference = new MessageReference();
					mMessageReference.accountUuid = mAccount.getUuid();
					mMessageReference.folderName = segmentList.get(1);
					mMessageReference.uid = segmentList.get(2);

					mMessageReferences = new ArrayList<MessageReference>();
				}
				else
				{
					//TODO: Use resource to externalize message
					Toast.makeText(this, "Invalid intent uri: " + uri.toString(), Toast.LENGTH_LONG).show();
					return;
				}
			}
		}
		if (Secure9.DEBUG)
			Log.d(Secure9.LOG_TAG, "MessageView got message " + mMessageReference);

		next = findViewById(R.id.next);
		previous = findViewById(R.id.previous);

		setOnClickListener(R.id.next);
		setOnClickListener(R.id.previous);

		next_scrolling = findViewById(R.id.next_scrolling);
		previous_scrolling = findViewById(R.id.previous_scrolling);


		boolean goNext = intent.getBooleanExtra(EXTRA_NEXT, false);
		if (goNext)
		{
			next.requestFocus();
		}
		// Perhaps the hideButtons should be global, instead of account-specific
		mAccount = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
		Account.HideButtons hideButtons = mAccount.getHideMessageViewButtons();

		//MessagingController.getInstance(getApplication()).addListener(mListener);
		if (Account.HideButtons.ALWAYS == hideButtons)
		{
			hideButtons();
		}
		else if (Account.HideButtons.NEVER == hideButtons)
		{
			showButtons();
		}
		else   // Account.HideButtons.KEYBOARD_AVAIL
		{
			final Configuration config = this.getResources().getConfiguration();
			if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)
			{
				hideButtons();
			}
			else
			{
				showButtons();
			}
		}
		displayMessage(mMessageReference);





	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		outState.putSerializable(EXTRA_MESSAGE_REFERENCE, mMessageReference);
		outState.putSerializable(EXTRA_MESSAGE_REFERENCES, mMessageReferences);
	}

	private void displayMessage(MessageReference ref)
	{
		mMessageReference = ref;
		if (Secure9.DEBUG)
			Log.d(Secure9.LOG_TAG, "MessageView displaying message " + mMessageReference);

		mAccount = Preferences.getPreferences(this).getAccount(ref.accountUuid);

		mMessageContentView.getSettings().setBlockNetworkImage(true);
		Secure9.setBlockNetworkLoads(mMessageContentView.getSettings(), true);

		mAttachments.removeAllViews();
		findSurroundingMessagesUid();


		boolean enableNext = (mNextMessage != null);
		boolean enablePrev = (mPreviousMessage != null);

		if (next.isEnabled() != enableNext)
			next.setEnabled(enableNext);
		if (previous.isEnabled() != enablePrev)
			previous.setEnabled(enablePrev);

		if (next_scrolling != null && (next_scrolling.isEnabled() != enableNext))
			next_scrolling.setEnabled(enableNext);
		if (previous_scrolling != null && (previous_scrolling.isEnabled() != enablePrev))
			previous_scrolling.setEnabled(enablePrev);

		MessagingController.getInstance(getApplication()).loadMessageForView(
				mAccount,
				mMessageReference.folderName,
				mMessageReference.uid,
				mListener);

		mTopView.scrollTo(0, 0);
		mMessageContentView.scrollTo(0, 0);


	}


	private void showButtons()
	{
		View buttons = findViewById(R.id.scrolling_buttons);
		if (buttons != null)
		{
			buttons.setVisibility(View.GONE);
		}
	}

	private void hideButtons()
	{
		View buttons = findViewById(R.id.bottom_buttons);
		if (buttons != null)
		{
			buttons.setVisibility(View.GONE);
		}
	}

	private void setOnClickListener(int viewCode)
	{
		View thisView = findViewById(viewCode);
		if (thisView != null)
		{
			thisView.setOnClickListener(this);
		}
	}

	private void findSurroundingMessagesUid()
	{
		mNextMessage = mPreviousMessage = null;
		int i = mMessageReferences.indexOf(mMessageReference);
		if (i < 0)
			return;
		if (i != 0)
			mNextMessage = mMessageReferences.get(i - 1);
		if (i != (mMessageReferences.size() - 1))
			mPreviousMessage = mMessageReferences.get(i + 1);
	}

	@Override
	public void onResume()
	{
		super.onResume();
	}

	private void onDelete()
	{
		if (mMessage != null)
		{
			Message messageToDelete = mMessage;

			if (Secure9.messageViewReturnToList())
			{
				finish();
			}
			else
			{
				showNextMessage();
			}

			MessagingController.getInstance(getApplication()).deleteMessages(
					new Message[] { messageToDelete },
					null);
		}
	}

	private void showNextMessage()
	{
		findSurroundingMessagesUid();
		mMessageReferences.remove(mMessageReference);

		if (mLastDirection == NEXT && mNextMessage != null)
		{
			onNext(Secure9.isAnimations());
		}
		else if (mLastDirection == PREVIOUS && mPreviousMessage != null)
		{
			onPrevious(Secure9.isAnimations());
		}
		else if (mNextMessage != null)
		{
			onNext(Secure9.isAnimations());
		}
		else if (mPreviousMessage != null)
		{
			onPrevious(Secure9.isAnimations());
		}
		else
		{
			finish();
		}
	}

	private void onClickSender()
	{		

		if (mMessage != null)
		{
			try
			{
				Address senderEmail = mMessage.getFrom()[0];
				Uri contactUri = Uri.fromParts("mailto", senderEmail.getAddress(), null);

				Intent contactIntent = new Intent(Contacts.Intents.SHOW_OR_CREATE_CONTACT);
				contactIntent.setData(contactUri);

				// Pass along full E-mail string for possible create dialog
				contactIntent.putExtra(Contacts.Intents.EXTRA_CREATE_DESCRIPTION,
						senderEmail.toString());

				// Only provide personal name hint if we have one
				String senderPersonal = senderEmail.getPersonal();
				if (senderPersonal != null)
				{
					contactIntent.putExtra(Intents.Insert.NAME, senderPersonal);
				}

				startActivity(contactIntent);
			}
			catch (MessagingException me)
			{
				if (Config.LOGV)
				{
					Log.v(Secure9.LOG_TAG, "loadMessageForViewHeadersAvailable", me);
				}
			}
		}
	}

	private void onReply()
	{
		if (mMessage != null)
		{
			MessageCompose.actionReply(this, mAccount, mMessage, false);
			finish();
		}
	}

	private void onReplyAll()
	{
		if (mMessage != null)
		{
			MessageCompose.actionReply(this, mAccount, mMessage, true);
			finish();
		}
	}

	private void onForward()
	{
		if (mMessage != null)
		{
			MessageCompose.actionForward(this, mAccount, mMessage);
			finish();
		}
	}

	private void onFlag()
	{
		if (mMessage != null)
		{
			MessagingController.getInstance(getApplication()).setFlag(mAccount,
					mMessage.getFolder().getName(), new String[] { mMessage.getUid() }, Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED));
			try
			{
				mMessage.setFlag(Flag.FLAGGED, !mMessage.isSet(Flag.FLAGGED));
				setHeaders(mAccount, mMessage.getFolder().getName(), mMessage.getUid(), mMessage);
				prepareMenuItems();
			}
			catch (MessagingException me)
			{
				Log.e(Secure9.LOG_TAG, "Could not set flag on local message", me);
			}
		}
	}

	private void onMove()
	{
		if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false)
		{
			return;
		}
		if (MessagingController.getInstance(getApplication()).isMoveCapable(mMessage) == false)
		{
			Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
			toast.show();
			return;
		}
		Intent intent = new Intent(this, ChooseFolder.class);
		intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
		intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.folderName);
		intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference);
		startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE);
	}

	private void onCopy()
	{
		if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false)
		{
			return;
		}
		if (MessagingController.getInstance(getApplication()).isCopyCapable(mMessage) == false)
		{
			Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG);
			toast.show();
			return;
		}
		Intent intent = new Intent(this, ChooseFolder.class);
		intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
		intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mMessageReference.folderName);
		intent.putExtra(ChooseFolder.EXTRA_MESSAGE, mMessageReference);
		startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY);
	}

	private void onShowAdditionalHeaders()
	{
		int currentVisibility = mAdditionalHeadersView.getVisibility();

		if (currentVisibility == View.VISIBLE)
		{
			mHandler.hideAdditionalHeaders();
		}
		else
		{
			mHandler.showAdditionalHeaders();
		}
	}

	private List<HeaderEntry> getAdditionalHeaders(final Message message)
	throws MessagingException
	{
		List<HeaderEntry> additionalHeaders = new LinkedList<HeaderEntry>();

		/*
		 * Remove "Subject" header as it is already shown in the standard
		 * message view header. But do show "From", "To", and "Cc" again.
		 * This time including the email addresses. See issue 1805.
		 */
		Set<String> headerNames = new HashSet<String>(message.getHeaderNames());
		headerNames.remove("Subject");

		for (String headerName : headerNames)
		{
			String[] headerValues = message.getHeader(headerName);
			for (String headerValue : headerValues)
			{
				additionalHeaders.add(new HeaderEntry(headerName, headerValue));
			}
		}
		return additionalHeaders;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode)
		{
		case ACTIVITY_CHOOSE_FOLDER_MOVE:
		case ACTIVITY_CHOOSE_FOLDER_COPY:
			if (data == null)
				return;
			String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
			String srcFolderName = data.getStringExtra(ChooseFolder.EXTRA_CUR_FOLDER);
			MessageReference ref = (MessageReference)data.getSerializableExtra(ChooseFolder.EXTRA_MESSAGE);

			if (mMessageReference.equals(ref))
			{

				switch (requestCode)
				{
				case ACTIVITY_CHOOSE_FOLDER_MOVE:
					Message messageToMove = mMessage;

					showNextMessage();

					MessagingController.getInstance(getApplication()).moveMessage(mAccount,
							srcFolderName, messageToMove, destFolderName, null);
					break;
				case ACTIVITY_CHOOSE_FOLDER_COPY:
					MessagingController.getInstance(getApplication()).copyMessage(mAccount,
							srcFolderName, mMessage, destFolderName, null);
					break;
				}
			}
		}
	}


	private void onSendAlternate()
	{
		if (mMessage != null)
		{
			MessagingController.getInstance(getApplication()).sendAlternate(this, mAccount, mMessage);

		}
	}

	@Override
	protected void onNext(boolean animate)
	{
		if (mNextMessage == null)
		{
			Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show();
			return;
		}
		mLastDirection = NEXT;
		if (animate)
		{
			mTopView.startAnimation(outToLeftAnimation());
		}
		displayMessage(mNextMessage);
		next.requestFocus();

	}

	@Override
	protected void onPrevious(boolean animate)
	{
		if (mPreviousMessage == null)
		{
			Toast.makeText(this, getString(R.string.end_of_folder), Toast.LENGTH_SHORT).show();
			return;
		}

		mLastDirection = PREVIOUS;
		if (animate)
		{
			mTopView.startAnimation(inFromRightAnimation());
		}
		displayMessage(mPreviousMessage);
		previous.requestFocus();
	}

	private void onMarkAsUnread()
	{

		if (mMessage != null)
		{
			MessagingController.getInstance(getApplication()).setFlag(
					mAccount,
					mMessageReference.folderName,
					new String[] { mMessage.getUid() },
					Flag.SEEN,
					false);
			try
			{
				mMessage.setFlag(Flag.SEEN, false);
				setHeaders(mAccount, mMessage.getFolder().getName(), mMessage.getUid(), mMessage);
			}
			catch (Exception e)
			{
				Log.e(Secure9.LOG_TAG, "Unable to unset SEEN flag on message", e);
			}
		}
	}

	/**
	 * Creates a unique file in the given directory by appending a hyphen
	 * and a number to the given filename.
	 * @param directory
	 * @param filename
	 * @return
	 */
	private File createUniqueFile(File directory, String filename)
	{
		File file = new File(directory, filename);
		if (!file.exists())
		{
			return file;
		}
		// Get the extension of the file, if any.
		int index = filename.lastIndexOf('.');
		String format;
		if (index != -1)
		{
			String name = filename.substring(0, index);
			String extension = filename.substring(index);
			format = name + "-%d" + extension;
		}
		else
		{
			format = filename + "-%d";
		}
		for (int i = 2; i < Integer.MAX_VALUE; i++)
		{
			file = new File(directory, String.format(format, i));
			if (!file.exists())
			{
				return file;
			}
		}
		return null;
	}

	private void onDownloadAttachment(Attachment attachment)
	{
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			/*
			 * Abort early if there's no place to save the attachment. We don't want to spend
			 * the time downloading it and then abort.
			 */
			Toast.makeText(this,
					getString(R.string.message_view_status_attachment_not_saved),
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (mMessage != null)
		{
			MessagingController.getInstance(getApplication()).loadAttachment(
					mAccount,
					mMessage,
					attachment.part,
					new Object[] { true, attachment },
					mListener);
		}
	}

	private void onViewAttachment(Attachment attachment)
	{
		if (mMessage != null)
		{
			MessagingController.getInstance(getApplication()).loadAttachment(
					mAccount,
					mMessage,
					attachment.part,
					new Object[] { false, attachment },
					mListener);
		}
	}

	private void onShowPictures()
	{
		Secure9.setBlockNetworkLoads(mMessageContentView.getSettings(), false);
		mMessageContentView.getSettings().setBlockNetworkImage(false);
		mShowPicturesSection.setVisibility(View.GONE);
	}


	public void onClick(View view)
	{
		switch (view.getId())
		{
		case R.id.from:
			onClickSender();
			break;
		case R.id.reply:
		case R.id.reply_scrolling:
			onReply();
			break;
		case R.id.reply_all:
			onReplyAll();
			break;
		case R.id.decrypt:
			try {
				onDecrypt();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.delete:
		case R.id.delete_scrolling:
			onDelete();
			break;
		case R.id.forward:
		case R.id.forward_scrolling:
			onForward();
			break;
		case R.id.next:
		case R.id.next_scrolling:
			onNext(Secure9.isAnimations());
			break;
		case R.id.previous:
		case R.id.previous_scrolling:
			onPrevious(Secure9.isAnimations());
			break;
		case R.id.download:
			onDownloadAttachment((Attachment) view.getTag());
			break;
		case R.id.view:
			onViewAttachment((Attachment) view.getTag());
			break;
		case R.id.show_pictures:
			onShowPictures();
			break;
		case R.id.header_container:
			onShowAdditionalHeaders();
			break;
		}
	}


	private String cleanHTML(String textIn)
	{
		String text = textIn;

		// Remove HTML tag from java String   
		String noHTMLString = text.replaceAll("\\<.*?\\>", " ");

		// Remove Carriage return from java String
		noHTMLString = noHTMLString.replaceAll("<br/>", "\n");
		noHTMLString = noHTMLString.replaceAll("<br>", "\n");


		//mine
		noHTMLString = noHTMLString.replaceAll("&lt;", "<");
		noHTMLString = noHTMLString.replaceAll("&gt;", ">");


		// Remove New line from java string and replace html break
		noHTMLString = noHTMLString.replaceAll("\n", " ");
		noHTMLString = noHTMLString.replaceAll("&#39;", "\'");
		noHTMLString = noHTMLString.replaceAll("&quot;", "\"");

		return noHTMLString;

	}

	private String parseMessage(String text) 
	{
		int i = 0;
		final int SUBSTRING_CUTOFF = 18;
		String str = "";
		if(text.contains("BEGIN CIPHERTEXT: ")) 
		{
			while (!text.substring(0).startsWith("BEGIN CIPHERTEXT: ")) 
				text = text.substring(1);
			
			i = 0;
			text = text.substring(SUBSTRING_CUTOFF);
			while (!text.substring(i).startsWith(" :END CIPHERTEXT")) 
				str += text.charAt(i++);
			
			return str;
		}
		else
			return null;
	}
	/*
	 * getPassword() asks the user for a one-time encryption password.
	 * Called by onDecrypt if no key exists for recipient.  Calls encryptAction()
	 * when user clicks ok.
	 */

	private void getPassword(){


		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Decryption password");
		alert.setMessage(R.string.password_decrypt_text);

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		input.setTransformationMethod
		(android.text.method.PasswordTransformationMethod.getInstance());
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int whichButton) 
			{
				char[] password;
				password = new char[input.getText().length()];
				for(int i = 0; i < input.getText().length(); i++)
					password[i] = input.getText().charAt(i);

				// call decrypt action.  Still need to change password to char[]
				if(password.length == 16){
					//Call decrypt
					new Decryption(password).execute();
				}
				else{
					Toast.makeText(getApplicationContext(), R.string.password_length_error, Toast.LENGTH_LONG).show();
					if(password != null)
						Arrays.fill(password, '0');

				}
			}
		});

		alert.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.setIcon(R.drawable.encrypted);
		alert.show();

	}



	/*
	 *This thread process the Decryption.  A seperate thread is necessary
	 *to update/use the progress dialog.
	 */
	private class Decryption extends AsyncTask<String, char[], String>
	{
		//Local variables
		private ProgressDialog pd = new ProgressDialog(MessageView.this);
		private String message;
		private String subject;
		private char[] message2;
		char[] localPassword;

		public Decryption(char[] password)
		{
			localPassword = password;			
		}


		protected void onPreExecute()
		{    
			//Set up progress dialog
			if(aes256)
				pd.setMessage(MessageView.this.getString(R.string.decrypting_256));
			else
				pd.setMessage(MessageView.this.getString(R.string.decrypting));
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);			
			onProgressUpdate(10);
			pd.show();
		}

		protected void onProgressUpdate(int progress)
		{
			//Set progress dialog (update)
			pd.setProgress(progress);
		}

		protected String doInBackground(String... params) {



			try {    	

				//Retrieve message pieces           
				Part part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
				LocalTextBody body = (LocalTextBody)part.getBody();           
				message = MessagingController.getLocalMessage().toString();
				subject = mSubjectView.getText().toString();				
				message = cleanHTML(body.getBodyForDisplay().toString());

				if(!message.contains("BEGIN CIPHERTEXT:") && !message.contains(":END CIPHERTEXT"))
					noCipherText = true;				
				//Sets text equal to just the ciphertext. Uses cleanHTML.
				onProgressUpdate(20);


				if(message.contains("--Encrypted with Secure9 Mail for Android") && !mSubjectView.getText().equals("(No subject)"))
				{
					subject = new String(Base64.decode(subject.getBytes()));
					subjectIsEncrypted = true;
				}

				message = parseMessage(message);

				//Bridge between 0.8.54 and newer: convert to base64 only if necessary
				if(!message.contains("-"))
					message = new String(Base64.decode(message.getBytes()));

				if (message == null)
					throw new Exception(MessageView.this.getString(R.string.error_unsupported_ciphertext));	
				if(!noCipherText){
					//decrypt Message
					String t = message;
					String[] stArr = t.split(" ");
					byte[] key = Hash.charsToBytes(localPassword);
					//	byte[] key = String.valueOf(password).getBytes();
					Encryptor e = new Encryptor(key);
					byte[] byteMe = new byte[stArr.length];
					onProgressUpdate(40);
					for (int i = 0; i < stArr.length; i++) {
						byteMe[i] = Byte.parseByte(stArr[i]);

						if(stArr.length - i < (stArr.length/2))
							onProgressUpdate(50);
					} 
					onProgressUpdate(60);

					message = e.decryptString(byteMe);
					message2 = message.toCharArray();


					//This is a bad way to test if the subject is encrypted...
					//Need a more graceful option here.
					char[] test = subject.toCharArray();
					int numberOfOtherChars =0;
					for(int i=0; i<test.length;i++){
						if(!Character.isDigit(test[i]) && test[i] != '-' && test[i] != ' ')
							numberOfOtherChars++;
						i= test.length; //Exit loop when first "other" character is found
					}

					if(numberOfOtherChars != 0)
						subjectIsEncrypted = false;
					else
						subjectIsEncrypted = true;

					onProgressUpdate(75);


					//Decrypt subject if it's encrypted
					if(subjectIsEncrypted == true){
						subject = cleanHTML(subject.toString());
						String s = subject;
						String[] subArr = s.split(" ");
						byte[] byteMeSubject = new byte[subArr.length];
						onProgressUpdate(65);
						for (int i = 0; i < subArr.length; i++) {
							byteMeSubject[i] = Byte.parseByte(subArr[i]);
						} 
						subject = e.decryptString(byteMeSubject);

					}

					onProgressUpdate(90);
					byte[] filler= "0".getBytes();
					Arrays.fill(key, filler[0]);
					return "no error";
				}
			}
			catch(Exception f)
			{
				return f.getMessage();
			}
			return "";


		}

		protected void onPostExecute(String error)
		{

			onProgressUpdate(99);
			//Zeroize password or pin
			if(localPassword != null)
				Arrays.fill(localPassword, '0');

			pd.dismiss();
			if(noCipherText)
				Toast.makeText(MessageView.this, MessageView.this.getString(R.string.error_unsupported_ciphertext), Toast.LENGTH_SHORT).show();

			else if(!error.equals("no error") && !noCipherText)
				Toast.makeText(MessageView.this, error, Toast.LENGTH_SHORT).show();			

			else
			{
				//Create dialog pop up      
				AlertDialog.Builder decryptedContent= new AlertDialog.Builder(MessageView.this);
				decryptedContent.setMessage(new String(message2))
				.setCancelable(false)
				.setPositiveButton(R.string.close_action, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'Yes' Button
						dialog.cancel();
						Toast.makeText(MessageView.this, MessageView.this.getString(R.string.close_deciphered), Toast.LENGTH_LONG).show();

					}
				})
				.setNegativeButton(R.string.save_locally_btn, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int id){
						//Action for No button
						dialog.cancel();
						Toast.makeText(MessageView.this, MessageView.this.getString(R.string.save_locally), Toast.LENGTH_LONG).show();

					}
				});
				AlertDialog decryptedDialog = decryptedContent.create();
				decryptedDialog.setTitle(new String(subject));
				decryptedDialog.setIcon(R.drawable.decrypted);
				decryptedDialog.show();
			}
			noCipherText = false;
		}



	}

	//Retreive key from file and pass it to Decryption thread.
	//If pin verification is enabled, verifyPin() calls this, otherwise
	//directly from onDecrypt().
	private void decryptWithKey()
	{
		char[] password;
		Address[] from = null;

		try 
		{
			from = mMessage.getFrom();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sender = Address.toAddress(from);
		EncryptionNewKey.remoteEmailSource = sender;


		try 
		{
			FileInputStream fis = openFileInput((mAccount.getEmail() + sender + 
					this.getString(R.string.complete_key_file_type)).toLowerCase());
			BufferedReader in = new BufferedReader(new InputStreamReader(fis));
			//Read key file as char[] only... Would be MUCH cleaner if we used strings. (but not safe for keying material)
			char[] keyChars = new char[2500];
			int r;
			int index = 0;
			while ((r = in.read()) != -1) 
			{
				keyChars[index] = (char) r;
				index++;
			}

			//find third index of OO to get key
			int delimiterIndex = -1;
			int delimitersFound = 0;
			for(int i = 0; i < keyChars.length - 1; i++)
			{
				if(keyChars[i] == 'O' && keyChars[i++] == 'O')
				{
					delimitersFound++;
					if(delimitersFound == 3)
						delimiterIndex = i + 1; //+1 so index starts at actual key value rather than O.
				}
			}

			char[] key = new char[1500];
			int keyIndex = 0; //Index for actual key array
			boolean endOfKey = false;//True when loop reaches next OO.

			//Begin at keyChars index of 2nd 'OO'.
			try
			{
				for(int i = delimiterIndex; i < keyChars.length - 2; i++)
				{
					//Add  3rd through 4th OO key values to key char[]
					if(keyChars[i] != 'O' && !endOfKey)
					{
						key[keyIndex] =  keyChars[i];
						keyIndex++;
					}
					else
						endOfKey = true; //When loop reaches next OO, end of key is true.
				}
				if(keyChars != null)
					Arrays.fill(keyChars, '0');
			}
			catch(ArrayIndexOutOfBoundsException a)
			{
				Toast.makeText(this, a.getLocalizedMessage() + "out of bounds",Toast.LENGTH_LONG).show();
			}


			//Retrieve message pieces           
			String message = "";
			Part part;
			try 
			{
				part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
				LocalTextBody body = (LocalTextBody)part.getBody();           
				message = MessagingController.getLocalMessage().toString();
				message = cleanHTML(body.getBodyForDisplay().toString()); 
			} 
			catch (MessagingException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//Determine which key to use- 128 or 256
			if(message.contains("Encrypted with Secure9 Mail for Android."))
			{
				//256 bit
				aes256 = true;
				password = new char[32];
				for(int i = 0; i < 32; i++)
					password[i]=key[i];
			}
			else if(message.contains("Encrypted with Secure9 Mail for Android"))
			{
				//128 bit
				password = new char[16];
				for(int i = 0; i < 16; i++)
					password[i]=key[i];			
			}
			//Should never happen, but has to be initialized to avoid null pointer
			else
				password = new char[1]; 

			if(key != null)
				Arrays.fill(key, '0');
			in.close();
		} 
		catch (FileNotFoundException e) 
		{
			Toast.makeText(MessageView.this,
					"FILE NOT FOUND",
					Toast.LENGTH_LONG).show();
			password = new char[1];

		} 
		catch (IOException e) 
		{
			Toast.makeText(MessageView.this,
					"IOException",
					Toast.LENGTH_LONG).show();
			password = new char[1];

		}



		new Decryption(password).execute();
	}


	private void verifyPin()
	{
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(this.getString(R.string.verify_pin_dialog_title));
		alert.setMessage(this.getString(R.string.verify_pin_dialog_text));

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		input.setInputType(InputType.TYPE_CLASS_PHONE);
		input.setTransformationMethod

		(android.text.method.PasswordTransformationMethod.getInstance());
		alert.setView(input);

		alert.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) 
			{

				char[] inputPin1 = new char[input.getText().length()];
				for(int i = 0; i < input.getText().length(); i++)
					inputPin1[i] = input.getText().charAt(i);

				FileInputStream fis;
				try 
				{
					fis = openFileInput((mAccount.getEmail().toLowerCase()) + MessageView.this.getString(R.string.legacy_pin_file_type));
					BufferedReader in = new BufferedReader(new InputStreamReader(fis));	
					char[] pin = in.readLine().toCharArray();

					if (Arrays.equals(pin, inputPin1))								
						decryptWithKey();						


					else
						Toast.makeText(MessageView.this, R.string.pin_incorrect,Toast.LENGTH_LONG).show();

					if(inputPin1 !=  null)
						Arrays.fill(inputPin1, '0');

				} 
				catch (FileNotFoundException e) 
				{
					//No .pin found, try .pin2
					try 
					{
						fis = openFileInput((mAccount.getEmail().toLowerCase()) + MessageView.this.getString(R.string.hashed_pin_file_type));
						BufferedReader in = new BufferedReader(new InputStreamReader(fis));	
						String hashFromFile = in.readLine();
						String storedRand = Hash.getRandom(hashFromFile, input.getText().length(), MessageView.this);
						String storedStatic = Hash.getStatic(hashFromFile, input.getText().length(), MessageView.this);


						char[] inputPin2 = new char[input.getText().length()];
						for(int i = 0; i < input.getText().length(); i++)
							inputPin2[i] = input.getText().charAt(i);


						String inputHash = Hash.verify(mAccount.getEmail(), 
								inputPin2, storedRand, storedStatic);

						if(inputHash.equals(hashFromFile))
							decryptWithKey();	
						else
							Toast.makeText(MessageView.this,R.string.pin_incorrect,Toast.LENGTH_LONG).show();
						
						if(inputPin2 != null)
							Arrays.fill(inputPin2, '0');

					} catch (FileNotFoundException e1) {
						Toast.makeText(MessageView.this, R.string.pin_not_found,Toast.LENGTH_LONG).show();

					} catch (IOException e1) {
						Toast.makeText(MessageView.this, R.string.error_key_io,Toast.LENGTH_LONG).show();
					}

				} catch (IOException e) {
					Toast.makeText(MessageView.this, R.string.error_key_io,Toast.LENGTH_LONG).show();
				}

			} 

		});

		alert.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.

			}
		});

		alert.setIcon(R.drawable.pin);
		alert.show();
	}

	//Setup for received key request.  Receiver of a DH key request
	//Completes this step, and it is the only step required for the key to
	//be usable to this party.
	private void setupReceivedKey()
	{		
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which){
				case DialogInterface.BUTTON_POSITIVE: 
					//Get sender address
					Address[] from = null;
					try 
					{
						from = mMessage.getFrom();
					} 
					catch (MessagingException e) 
					{
						Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
					}
					String sender = Address.toAddress(from);

					//Retreive message body   
					Part part = null;
					String message = "";
					try 
					{
						part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
						LocalTextBody body = (LocalTextBody)part.getBody();  
						message = MessagingController.getLocalMessage().toString();
						message = cleanHTML(body.getBodyForDisplay().toString());

					} 
					catch (MessagingException e) 
					{
						Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
					}	

					String[] values = message.split("OO");
					
					MessageView.this.deleteFile(mAccount.getEmail().toString() +
							sender + MessageView.this.getString(R.string.initial_key_file_type));

					DiffieHellman dh = new DiffieHellman(new BigInteger(values[1]), new BigInteger(values[2]));
					String FILENAME = (mAccount.getEmail() + sender + MessageView.this.getString(R.string.complete_key_file_type)).toLowerCase();
					try 
					{			
						FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
						fos.write((sender + "\n" + mAccount.getEmail() + "\nOO").getBytes());
						fos.write((dh.getPublicKey() + "OO").getBytes());
						fos.write((dh.getPrivateKey() + "OO").getBytes());
						fos.write((dh.getSharedSecret(new BigInteger(values[3])) + "OO").getBytes());
						fos.close();
						Keys.keyList.add((mAccount.getEmail() + sender + MessageView.this.getString(R.string.complete_key_file_type)).toLowerCase());
						Toast.makeText(MessageView.this, R.string.key_saved, Toast.LENGTH_LONG).show();
						Toast.makeText(MessageView.this, "You may now encrypt/decrypt with this key.", Toast.LENGTH_LONG).show();

						try 
						{
							
							MessageCompose.replyPublicKey(MessageView.this, from, mAccount, dh);
							Toast.makeText(MessageView.this, "Your public key has been sent to the originator of this request.", Toast.LENGTH_LONG).show();
						} 
						catch (MessagingException e) 
						{
							Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
						}


					} 
					catch (FileNotFoundException e) 
					{
						// TODO Auto-generated catch block
						Log.v("Fie not found", e.getLocalizedMessage());
					} 
					catch (IOException e) 
					{
						// TODO Auto-generated catch block
						Log.v("IO Exception",e.getLocalizedMessage());

					}
					
					Arrays.fill(values, "0");
					//	EncryptionNewKey.actionNewKey(MessageView.this,mAccount,"receive");
				case DialogInterface.BUTTON_NEGATIVE:						
					//Cancel
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Would you like to set up a new key with " + sender + "?"					
		).setPositiveButton(R.string.yes_action, dialogClickListener)
		.setNegativeButton(R.string.no_action, dialogClickListener)
		.setIcon(R.drawable.key_good).setTitle("Key Setup").show();
	}

	//Finish key setup from key setup reply (with remote public key).
	//Last step in DH key setup..  Originator of the key setup request
	//completes this step.
	private void finishSentKeySetup()
	{	

		String line = "";
		String key = "";


		//Scan for and delete initial keys.  Only applies if user is
		//Setting up a key with themselves.  Otherwise it is deleted
		//when the setup is finished.
		String initialFilename = (mAccount.getEmail().toString().toLowerCase() +
				sender + MessageView.this.getString(R.string.initial_key_file_type));

		Keys.refreshInitialKeys(this);

		if(Keys.initialKeys.contains(initialFilename))
		{
			try 
			{
				FileInputStream fis2 = openFileInput((mAccount.getEmail() + sender + this.getString(R.string.initial_key_file_type).toLowerCase()));
				BufferedReader in2 = new BufferedReader(new InputStreamReader(fis2));
				//Read key file into one string, which we will then split.
				line = in2.readLine();
				while(line != null)
				{
					key = key + line;
					line = in2.readLine();
				}
			} 
			catch (FileNotFoundException e) 
			{
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			} 
			catch (IOException e) 
			{
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			}

			String[] storedValues = key.split("OO");
			/*The following is how the keys are split.  References
			 *To these are used as the array call specifically to avoid 
			 *using new string objects (security). 
			 */

			// modulus = storedValues[1];
			// generator = storedValues[2];
			// publicKey = storedValues[3];
			// privateKey = storedValues[4];

			//Retreive message body from email
			Part part = null;
			String message = "";
			try 
			{
				part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
				LocalTextBody body = (LocalTextBody)part.getBody();  
				message = MessagingController.getLocalMessage().toString();
				message = cleanHTML(body.getBodyForDisplay().toString());
			} 
			catch (MessagingException e) 
			{
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			}
			String[] receivedValues = message.split("OO");
			String remotePublic = receivedValues[1];
			DiffieHellman dh = new DiffieHellman();
			BigInteger sharedSecret = dh.getSharedSecret(new BigInteger(remotePublic),
					new BigInteger(storedValues[4]), new BigInteger(storedValues[1]));


			MessageView.this.deleteFile(mAccount.getEmail().toString() +
					sender + this.getString(R.string.initial_key_file_type));
			String FILENAME = (mAccount.getEmail().toString()  + 
					sender + this.getString(R.string.complete_key_file_type)).toLowerCase();
			try 
			{
				FileOutputStream fos2 = openFileOutput(FILENAME,Context.MODE_PRIVATE);
				fos2.write((sender + "\n" + mAccount.getEmail() + "\nOO").getBytes());
				fos2.write((storedValues[3] + "OO").getBytes());
				fos2.write((storedValues[4] + "OO").getBytes());
				fos2.write((sharedSecret + "OO").getBytes());
				fos2.close();
				Keys.keyList.add((mAccount.getEmail() + sender + this.getString(R.string.complete_key_file_type)).toLowerCase());
				Toast.makeText(MessageView.this, R.string.key_saved, Toast.LENGTH_LONG).show();
			} 
			catch (FileNotFoundException e) 
			{
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			} 
			catch (IOException e) 
			{
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			}
			
			Arrays.fill(storedValues, "0");
		}
		else
			Toast.makeText(MessageView.this, R.string.no_initial_key, Toast.LENGTH_LONG).show();

	}

	//Key revocation for received key
	private void revokeKey()
	{
		//Check for pin file
		pinMatch = Hash.pinExists(this, mAccount.getEmail());

		int icon = R.drawable.key_bad;
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Confirm Action");
		alert.setMessage(R.string.confirm_delete_key);
		if(pinMatch)
		{
			// Set an EditText view to get user input 
			input = new EditText(this);
			input.setInputType(InputType.TYPE_CLASS_PHONE);
			input.setTransformationMethod	
			(android.text.method.PasswordTransformationMethod.getInstance());
			alert.setView(input);
			alert.setMessage(R.string.pin_confirm_delete_key);

			icon = R.drawable.pin;

		}
		alert.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() 
		{
			public void onClick(DialogInterface dialog, int whichButton) 
			{
				if(pinMatch)
				{
					if(input.getText().length() < 4)
					{
						Toast.makeText(MessageView.this, R.string.pin_too_short, Toast.LENGTH_LONG).show();
						return;						
					}

					char[] pinInput = new char[input.getText().length()];
					for(int i = 0; i < input.getText().length(); i++)
						pinInput[i] = input.getText().charAt(i);



					FileInputStream fis;
					try 
					{
						fis = openFileInput((mAccount.getEmail().toLowerCase()) + MessageView.this.getString(R.string.legacy_pin_file_type));
						BufferedReader in = new BufferedReader(new InputStreamReader(fis));	
						char[] pinFromFile = in.readLine().toCharArray();


						if (pinFromFile.equals(pinInput)){								
							//Delete key file
							MessageView.this.deleteFile((mAccount.getEmail() + 
									sender + MessageView.this.getString(R.string.complete_key_file_type)).toLowerCase());	

							Toast.makeText(MessageView.this, R.string.key_deleted, Toast.LENGTH_LONG).show();
							Keys.refreshKeys(MessageView.this);
						}
						else
							Toast.makeText(MessageView.this,R.string.pin_incorrect,Toast.LENGTH_LONG).show();


						if(pinInput !=  null)
							Arrays.fill(pinInput, '0');
						if(pinFromFile !=  null)
							Arrays.fill(pinFromFile, '0');


					} 
					catch (FileNotFoundException e) 
					{
						//No .pin found, try .pin2
						try 
						{
							fis = openFileInput((mAccount.getEmail().toLowerCase()) + MessageView.this.getString(R.string.hashed_pin_file_type));
							BufferedReader in = new BufferedReader(new InputStreamReader(fis));	
							String pinFromFile = in.readLine();
							String storedRand = Hash.getRandom(pinFromFile, input.getText().length(), MessageView.this);
							String storedStatic = Hash.getStatic(pinFromFile, input.getText().length(), MessageView.this);

							char[] inputPin = new char[input.getText().length()];
							for(int i = 0; i < input.getText().length(); i++)
								inputPin[i] = input.getText().charAt(i);

							String inputHash = Hash.verify(mAccount.getEmail(), 
									inputPin, storedRand, storedStatic);



							if (inputHash.equals(pinFromFile)){								
								//Delete key file
								MessageView.this.deleteFile((mAccount.getEmail() + 
										sender + MessageView.this.getString(R.string.complete_key_file_type)).toLowerCase());	
								Toast.makeText(MessageView.this, R.string.key_deleted, Toast.LENGTH_LONG).show();
								Keys.refreshKeys(MessageView.this);
							}

							else
								Toast.makeText(MessageView.this,R.string.pin_incorrect,Toast.LENGTH_LONG).show();


							if(pinInput !=  null)
								Arrays.fill(pinInput, '0');

						} 
						catch (FileNotFoundException e1) 
						{
							Toast.makeText(MessageView.this,R.string.error_key_not_found,Toast.LENGTH_LONG).show();
						} 
						catch (IOException e1) 
						{
							Toast.makeText(MessageView.this,R.string.error_key_io,Toast.LENGTH_LONG).show();
						}
					} 
					catch (IOException e) 
					{
						Toast.makeText(MessageView.this,R.string.error_key_io,Toast.LENGTH_LONG).show();
					}
				}

				else
				{
					//Delete key file
					MessageView.this.deleteFile((mAccount.getEmail() + 
							sender + MessageView.this.getString(R.string.complete_key_file_type)).toLowerCase());	
					Toast.makeText(MessageView.this, R.string.key_deleted, Toast.LENGTH_LONG).show();
					Keys.refreshKeys(MessageView.this);
				}
			}

		});

		alert.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.

			}
		});

		alert.setIcon(icon);
		alert.show();


	}

	private void promptPasswordOrKey()
	{
		String alertMessage;
		int icon;
		int title;
		int keyButton;
		EncryptionNewKey.remoteEmailSource = sender;
		//Set up message strings - needs to be put into strings.xml
		if(Keys.keyExists(this, mAccount.getEmail(),sender) && !mAccount.getUseKeyDefault())
		{
			alertMessage = this.getString(R.string.key_found_prompt);
			icon = R.drawable.key_good;
			title = R.string.key_found_dialog_title;
			keyButton = R.string.key_found_use_key_btn;
		}
		else
		{
			alertMessage = this.getString(R.string.key_not_found_prompt) + sender;	
			icon = R.drawable.key_bad;
			title = R.string.key_not_found_dialog_title;
			keyButton = R.string.key_not_found_use_key_btn;
		}

		//Prompt user for choice between creating key or using password
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {	
				switch (which){
				// Action for user wanting to encrypt with one-time password.
				case DialogInterface.BUTTON_POSITIVE: 
					getPassword();
					break; 

					// Action for user wanting to set up new DH key for recipient
				case DialogInterface.BUTTON_NEGATIVE:
					if(Keys.keyExists(MessageView.this, mAccount.getEmail(),sender) && (mAccount.getAskForPin().equals("1")
							|| mAccount.getAskForPin().equals("2") ))
						verifyPin();
					else if(Keys.keyExists(MessageView.this, mAccount.getEmail(),sender))
						//Get "ask for pin when" and call appropriate methods here
						decryptWithKey();

					else if(!Keys.keyExists(MessageView.this, mAccount.getEmail(),sender))
					{							
						EncryptionNewKey.actionNewKey(MessageView.this, mAccount,"compose", sender);
					}
					break;
				}
			}
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(alertMessage).setPositiveButton(R.string.key_use_password_btn, dialogClickListener)
		.setNegativeButton(keyButton, dialogClickListener)
		.setIcon(icon).setTitle(title).show();
	}




	private void onDecrypt() throws MessagingException 
	{
		//Pull sender address from email
		Address[] from = null;
		try 
		{
			from = mMessage.getFrom();
		} 
		catch (MessagingException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sender = Address.toAddress(from);		
		EncryptionNewKey.remoteEmailSource = sender;
		String subject = mSubjectView.getText().toString();

		//Find automated key setup email and ask user if they want to setup key
		if(subject.equals(this.getString(R.string.subject_key_setup)))
		{
			if(Keys.keyExists(this, mAccount.getEmail().toString(), sender))	
				Toast.makeText(MessageView.this, "Key already exists.  Delete current key to recreate.", Toast.LENGTH_LONG).show();
			else
				setupReceivedKey();
		}
		//Find automated key setup email and ask user if they want to setup key
		else if(subject.equals(this.getString(R.string.subject_key_revocation)))
		{
			revokeKey();
		}
		else if(subject.equals(this.getString(R.string.subject_key_reply)))
		{
			if(Keys.keyExists(this, mAccount.getEmail().toString(), sender))	
				Toast.makeText(MessageView.this, "Key already exists.  Delete current key to recreate.", Toast.LENGTH_LONG).show();
			else
				finishSentKeySetup();
		}
		else
		{
			//Test for no ciphertext		  
			Part part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
			LocalTextBody body = (LocalTextBody)part.getBody();           
			String message = MessagingController.getLocalMessage().toString();
			subject = mSubjectView.getText().toString();				
			message = cleanHTML(body.getBodyForDisplay().toString());

			if((!message.contains("BEGIN CIPHERTEXT:") && !message.contains(":END CIPHERTEXT")) 
					|| !message.contains("Encrypted with Secure9 Mail for Android"))
			{
				Toast.makeText(this, "Invalid ciphertext format", Toast.LENGTH_LONG).show();
				return;
			}

			//if NO key exists or user selected always prompt, prompt user for choice of key (create or use) or password  		
			else if(!Keys.keyExists(this, mAccount.getEmail(),sender) || !mAccount.getUseKeyDefault())
				promptPasswordOrKey();

			else if(Keys.keyExists(this, mAccount.getEmail(),sender) && (mAccount.getAskForPin().equals("1")
					|| mAccount.getAskForPin().equals("2")))
				verifyPin();

			else if(Keys.keyExists(this, mAccount.getEmail(),sender))
				decryptWithKey();


		}
		EncryptionNewKey.remoteEmailSource = "";
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.delete:
			onDelete();
			break;
		case R.id.reply:
			onReply();
			break;
		case R.id.decrypt:
			try {
				onDecrypt();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.reply_all:
			onReplyAll();
			break;
		case R.id.forward:
			onForward();
			break;
		case R.id.send_alternate:
			onSendAlternate();
			break;
		case R.id.mark_as_unread:
			onMarkAsUnread();
			break;
		case R.id.flag:
			onFlag();
			break;
		case R.id.move:
			onMove();
			break;
		case R.id.copy:
			onCopy();
			break;
		case R.id.show_full_header:
			onShowAdditionalHeaders();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.message_view_option, menu);
		optionsMenu = menu;
		prepareMenuItems();
		if (MessagingController.getInstance(getApplication()).isCopyCapable(mAccount) == false)
		{
			menu.findItem(R.id.copy).setVisible(false);
		}
		if (MessagingController.getInstance(getApplication()).isMoveCapable(mAccount) == false)
		{
			menu.findItem(R.id.move).setVisible(false);
		}

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		prepareMenuItems();	
		return super.onPrepareOptionsMenu(menu);

	}

	private void prepareMenuItems()
	{
		Menu menu = optionsMenu;
		if (menu != null)
		{
			MenuItem flagItem = menu.findItem(R.id.flag);
			if (flagItem != null && mMessage != null)
			{
				flagItem.setTitle((mMessage.isSet(Flag.FLAGGED) ? R.string.unflag_action : R.string.flag_action));
			}

			MenuItem additionalHeadersItem = menu.findItem(R.id.show_full_header);
			if (additionalHeadersItem != null)
			{
				additionalHeadersItem.setTitle((mAdditionalHeadersView.getVisibility() == View.VISIBLE) ?
						R.string.hide_full_header_action : R.string.show_full_header_action);
			}
			menu.findItem(R.id.decrypt).setVisible(false);

		}
		

		//Secure9
		if(menu != null){	
			menu.findItem(R.id.decrypt).setVisible(false);
			String subject = mSubjectView.getText().toString();
			//Retrieve message pieces           
			String message = "";
			try {

				Part part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
				if(part != null){
					LocalTextBody body = (LocalTextBody)part.getBody(); 
					if(body != null)
						message = cleanHTML(body.getBodyForDisplay().toString());
				if(part == null || body == null)
					return;
				}

			} catch (MessagingException e) {
				Toast.makeText(MessageView.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			}

			if(subject != null && message != "")
			{
				
				if(subject.equals(this.getString(R.string.subject_key_setup))){
					menu.findItem(R.id.decrypt).setVisible(true);
					menu.findItem(R.id.decrypt).setTitle("Setup Key").setIcon(R.drawable.ic_menu_key_action);
					
				}
				else if(subject.equals(this.getString(R.string.subject_key_revocation))){
					menu.findItem(R.id.decrypt).setVisible(true);
					menu.findItem(R.id.decrypt).setTitle("Delete Key").setIcon(R.drawable.ic_menu_key_action);
				}
				else if(subject.equals(this.getString(R.string.subject_key_reply))){
					menu.findItem(R.id.decrypt).setVisible(true);
					menu.findItem(R.id.decrypt).setTitle("Finalize Key").setIcon(R.drawable.ic_menu_key_action);
				}

				else if((message.contains("BEGIN CIPHERTEXT:") && message.contains(":END CIPHERTEXT"))){
					menu.findItem(R.id.decrypt).setVisible(true);
					menu.findItem(R.id.decrypt).setTitle("Decrypt").setIcon(R.drawable.ic_menu_decrypt);
				}
				else 
					menu.findItem(R.id.decrypt).setVisible(false);
			}
		}
	}

	private Bitmap getPreviewIcon(Attachment attachment) throws MessagingException
	{
		try
		{
			return BitmapFactory.decodeStream(
					getContentResolver().openInputStream(
							AttachmentProvider.getAttachmentThumbnailUri(mAccount,
									attachment.part.getAttachmentId(),
									62,
									62)));
		}
		catch (Exception e)
		{
			/*
			 * We don't care what happened, we just return null for the preview icon.
			 */
			return null;
		}
	}

	/*
	 * Formats the given size as a String in bytes, kB, MB or GB with a single digit
	 * of precision. Ex: 12,315,000 = 12.3 MB
	 */
	public static String formatSize(float size)
	{
		long kb = 1024;
		long mb = (kb * 1024);
		long gb  = (mb * 1024);
		if (size < kb)
		{
			return String.format("%d bytes", (int) size);
		}
		else if (size < mb)
		{
			return String.format("%.1f kB", size / kb);
		}
		else if (size < gb)
		{
			return String.format("%.1f MB", size / mb);
		}
		else
		{
			return String.format("%.1f GB", size / gb);
		}
	}

	private void renderAttachments(Part part, int depth) throws MessagingException
	{
		String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
		String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
		String name = MimeUtility.getHeaderParameter(contentType, "name");
		if (name == null)
		{
			name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
		}
		if (name != null)
		{
			/*
			 * We're guaranteed size because LocalStore.fetch puts it there.
			 */
			int size = Integer.parseInt(MimeUtility.getHeaderParameter(contentDisposition, "size"));

			Attachment attachment = new Attachment();
			attachment.size = size;
			String mimeType = part.getMimeType();
			if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(mimeType))
			{
				mimeType = MimeUtility.getMimeTypeByExtension(name);
			}
			attachment.contentType = mimeType;
			attachment.name = name;
			attachment.part = (LocalAttachmentBodyPart) part;

			LayoutInflater inflater = getLayoutInflater();
			View view = inflater.inflate(R.layout.message_view_attachment, null);

			TextView attachmentName = (TextView)view.findViewById(R.id.attachment_name);
			TextView attachmentInfo = (TextView)view.findViewById(R.id.attachment_info);
			ImageView attachmentIcon = (ImageView)view.findViewById(R.id.attachment_icon);
			Button attachmentView = (Button)view.findViewById(R.id.view);
			Button attachmentDownload = (Button)view.findViewById(R.id.download);

			if ((!MimeUtility.mimeTypeMatches(attachment.contentType,
					Secure9.ACCEPTABLE_ATTACHMENT_VIEW_TYPES))
					|| (MimeUtility.mimeTypeMatches(attachment.contentType,
							Secure9.UNACCEPTABLE_ATTACHMENT_VIEW_TYPES)))
			{
				attachmentView.setVisibility(View.GONE);
			}
			if ((!MimeUtility.mimeTypeMatches(attachment.contentType,
					Secure9.ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES))
					|| (MimeUtility.mimeTypeMatches(attachment.contentType,
							Secure9.UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES)))
			{
				attachmentDownload.setVisibility(View.GONE);
			}

			if (attachment.size > Secure9.MAX_ATTACHMENT_DOWNLOAD_SIZE)
			{
				attachmentView.setVisibility(View.GONE);
				attachmentDownload.setVisibility(View.GONE);
			}

			attachment.viewButton = attachmentView;
			attachment.downloadButton = attachmentDownload;
			attachment.iconView = attachmentIcon;

			view.setTag(attachment);
			attachmentView.setOnClickListener(this);
			attachmentView.setTag(attachment);
			attachmentDownload.setOnClickListener(this);
			attachmentDownload.setTag(attachment);

			attachmentName.setText(name);
			attachmentInfo.setText(formatSize(size));

			Bitmap previewIcon = getPreviewIcon(attachment);
			if (previewIcon != null)
			{
				attachmentIcon.setImageBitmap(previewIcon);
			}
			else
			{
				attachmentIcon.setImageResource(R.drawable.attached_image_placeholder);
			}

			mHandler.addAttachment(view);
		}

		if (part.getBody() instanceof Multipart)
		{
			Multipart mp = (Multipart)part.getBody();
			for (int i = 0; i < mp.getCount(); i++)
			{
				renderAttachments(mp.getBodyPart(i), depth + 1);
			}
		}
	}

	private void setHeaders(Account account, String folder, String uid,
			final Message message) throws MessagingException
			{
		String subjectText = message.getSubject();
		String fromText = Address.toFriendly(message.getFrom());
		String dateText = getDateFormat().format(message.getSentDate());
		String timeText = getTimeFormat().format(message.getSentDate());
		String toText = Address.toFriendly(message.getRecipients(RecipientType.TO));
		String ccText = Address.toFriendly(message.getRecipients(RecipientType.CC));

		int color = mAccount.getChipColor();
		boolean hasAttachments = ((LocalMessage) message).getAttachmentCount() > 0;
		boolean isDownloading = !message.isSet(Flag.X_DOWNLOADED_FULL);
		boolean unread = !message.isSet(Flag.SEEN);

		mHandler.setHeaders(subjectText,
				fromText,
				dateText,
				timeText,
				toText,
				ccText,
				color,
				unread,
				hasAttachments,
				isDownloading,
				message.isSet(Flag.FLAGGED),
				message.isSet(Flag.ANSWERED));

		// Update additional headers display, if visible
		if (mAdditionalHeadersView.getVisibility() == View.VISIBLE)
		{
			mHandler.showAdditionalHeaders();
		}


			}

	class Listener extends MessagingListener
	{

		@Override
		public void loadMessageForViewHeadersAvailable(Account account, String folder, String uid,
				final Message message)
		{
			if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
					|| !mMessageReference.accountUuid.equals(account.getUuid()))
			{
				return;
			}

			MessageView.this.mMessage = message;
			if (!message.isSet(Flag.X_DOWNLOADED_FULL)
					&& !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
			{
				mHandler.post(new Runnable()
				{
					public void run()
					{
						mMessageContentView.loadUrl("file:///android_asset/downloading.html");
					}
				});
			}
			try
			{
				setHeaders(account, folder, uid, message);
			}
			catch (MessagingException me)
			{
				Log.e(Secure9.LOG_TAG, "loadMessageForViewHeadersAvailable", me);
			}
		}

		@Override
		public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
				Message message)
		{
			if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
					|| !mMessageReference.accountUuid.equals(account.getUuid()))
			{
				return;
			}

			try
			{
				if (MessageView.this.mMessage!=null
						&& MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL)
						&& message.isSet(Flag.X_DOWNLOADED_FULL))
				{

					setHeaders(account, folder, uid, message);
				}

				MessageView.this.mMessage = message;

				String text;
				Part part = MimeUtility.findFirstPartByMimeType(mMessage, "text/html");
				if (part == null)
				{
					part = MimeUtility.findFirstPartByMimeType(mMessage, "text/plain");
					if (part == null)
					{
						text = null;
					}
					else
					{
						LocalTextBody body = (LocalTextBody)part.getBody();
						if (body == null)
						{
							text = null;
						}
						else
						{
							text = body.getBodyForDisplay();
						}
					}
				}
				else
				{
					text = MimeUtility.getTextFromPart(part);
				}

				if (text != null)
				{
					/*
					 * TODO this should be smarter, change to regex for img, but consider how to
					 * get background images and a million other things that HTML allows.
					 */
					final String emailText = text;
					MessagingController.setLocalMessage(emailText);
					mHandler.post(new Runnable()
					{
						public void run()
						{
							mMessageContentView.loadDataWithBaseURL("email://", emailText, "text/html", "utf-8", null);
						}
					});
					mHandler.showShowPictures(text.contains("<img"));
				}
				else
				{
					mHandler.post(new Runnable()
					{
						public void run()
						{
							mMessageContentView.loadUrl("file:///android_asset/empty.html");
						}
					});
				}

				renderAttachments(mMessage, 0);
			}
			catch (Exception e)
			{
				if (Config.LOGV)
				{
					Log.v(Secure9.LOG_TAG, "loadMessageForViewBodyAvailable", e);
				}
			}
		}//loadMessageForViewBodyAvailable


		@Override
		public void loadMessageForViewFailed(Account account, String folder, String uid,
				final Throwable t)
		{
			if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
					|| !mMessageReference.accountUuid.equals(account.getUuid()))
			{
				return;
			}

			mHandler.post(new Runnable()
			{
				public void run()
				{
					setProgressBarIndeterminateVisibility(false);
					if (t instanceof IllegalArgumentException)
					{
						mHandler.invalidIdError();
					}
					else
					{
						mHandler.networkError();
					}
					if (!MessageView.this.mMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
					{
						mMessageContentView.loadUrl("file:///android_asset/empty.html");
					}
				}
			});
		}

		@Override
		public void loadMessageForViewFinished(Account account, String folder, String uid,
				Message message)
		{
			if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
					|| !mMessageReference.accountUuid.equals(account.getUuid()))
			{
				return;
			}

			mHandler.post(new Runnable()
			{
				public void run()
				{
					setProgressBarIndeterminateVisibility(false);
				}
			});
		}

		@Override
		public void loadMessageForViewStarted(Account account, String folder, String uid)
		{
			if (!mMessageReference.uid.equals(uid) || !mMessageReference.folderName.equals(folder)
					|| !mMessageReference.accountUuid.equals(account.getUuid()))
			{
				return;
			}

			mHandler.post(new Runnable()
			{
				public void run()
				{
					mMessageContentView.loadUrl("file:///android_asset/loading.html");
					setProgressBarIndeterminateVisibility(true);
				}
			});
		}

		@Override
		public void loadAttachmentStarted(Account account, Message message,
				Part part, Object tag, boolean requiresDownload)
		{
			if (mMessage!=message)
			{
				return;
			}

			mHandler.setAttachmentsEnabled(false);
			mHandler.progress(true);
			if (requiresDownload)
			{
				mHandler.fetchingAttachment();
			}
		}

		@Override
		public void loadAttachmentFinished(Account account, Message message,
				Part part, Object tag)
		{
			if (mMessage!=message)
			{
				return;
			}

			mHandler.setAttachmentsEnabled(true);
			mHandler.progress(false);

			Object[] params = (Object[]) tag;
			boolean download = (Boolean) params[0];
			Attachment attachment = (Attachment) params[1];

			if (download)
			{
				try
				{
					File file = createUniqueFile(Environment.getExternalStorageDirectory(),
							attachment.name);
					Uri uri = AttachmentProvider.getAttachmentUri(
							mAccount,
							attachment.part.getAttachmentId());
					InputStream in = getContentResolver().openInputStream(uri);
					OutputStream out = new FileOutputStream(file);
					IOUtils.copy(in, out);
					out.flush();
					out.close();
					in.close();
					mHandler.attachmentSaved(file.getName());
					new MediaScannerNotifier(MessageView.this, file);
				}
				catch (IOException ioe)
				{
					mHandler.attachmentNotSaved();
				}
			}
			else
			{
				Uri uri = AttachmentProvider.getAttachmentUri(
						mAccount,
						attachment.part.getAttachmentId());
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(uri);
				intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				try
				{
					startActivity(intent);
				}
				catch (Exception e)
				{
					Log.e(Secure9.LOG_TAG, "Could not display attachment of type " + attachment.contentType, e);
					Toast toast = Toast.makeText(MessageView.this, getString(R.string.message_view_no_viewer, attachment.contentType), Toast.LENGTH_LONG);
					toast.show();
				}
			}
		}

		@Override
		public void loadAttachmentFailed(Account account, Message message, Part part,
				Object tag, String reason)
		{
			if (mMessage!=message)
			{
				return;
			}

			mHandler.setAttachmentsEnabled(true);
			mHandler.progress(false);
			mHandler.networkError();
		}
	}

	class MediaScannerNotifier implements MediaScannerConnectionClient
	{
		private MediaScannerConnection mConnection;
		private File mFile;

		public MediaScannerNotifier(Context context, File file)
		{
			mFile = file;
			mConnection = new MediaScannerConnection(context, this);
			mConnection.connect();
		}

		public void onMediaScannerConnected()
		{
			mConnection.scanFile(mFile.getAbsolutePath(), null);
		}

		public void onScanCompleted(String path, Uri uri)
		{
			try
			{
				if (uri != null)
				{
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(uri);
					startActivity(intent);
				}
			}
			finally
			{
				mConnection.disconnect();
			}
		}
	}


	private Animation inFromRightAnimation()
	{
		return slideAnimation(0.0f, +1.0f);
	}

	private Animation outToLeftAnimation()
	{
		return slideAnimation(0.0f, -1.0f);
	}

	private Animation slideAnimation(float right, float left)
	{

		Animation slide = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  right, Animation.RELATIVE_TO_PARENT,  left,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		slide.setDuration(125);
		slide.setFillBefore(true);
		slide.setInterpolator(new AccelerateInterpolator());
		return slide;
	}
}
